package net.cassandraview.dbnav;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.thrift.TException;

import net.cassandraview.UserSession;

@ManagedBean(name = "databaseNavigation")
@SessionScoped
public class DatabaseNavigation {
	
	protected final Logger log = Logger.getLogger(DatabaseNavigation.class.getName());
	
	@ManagedProperty("#{userSession}")
	private UserSession session;
	
	private List<NavigationNode> navigationRoots = new ArrayList<NavigationNode>();
	
	@PostConstruct
	public void configure() {
		if (session != null) {
			Cassandra.Client dbClient = session.getClient();
			if (dbClient != null) {
				try {
					List<KsDef> keyspaces = dbClient.describe_keyspaces();
					navigationRoots = new ArrayList<NavigationNode>();
					for (KsDef ks : keyspaces) {
						NavigationNode node = new NavigationNode();
						node.setName(ks.getName());
						node.setType(NavigationNodeType.KEYSPACE);
						navigationRoots.add(node);
						List<CfDef> columnFamilies = ks.getCf_defs();
						for (CfDef cf : columnFamilies) {
							NavigationNode cf_node = new NavigationNode();
							cf_node.setName(cf.getName());
                            if ("Standard".equals(cf.column_type)) {
                                cf_node.setType(NavigationNodeType.COLUMN_FAMILY);
                                cf_node.setLeaf(true);
                            } else if ("Super".equals(cf.column_type)) {
                                cf_node.setType(NavigationNodeType.SUPER_COLUMN_FAMILY);
                            } else {
                                cf_node.setType(NavigationNodeType.UNKNOWN);
                            }
							cf_node.setParent(node);
							node.addChild(cf_node);
						}
					}
				} catch (Exception e) {
					log.log(Level.SEVERE, "Cannot get list of keyspaces from cassandra", e);
				}
			} else {
				log.log(Level.WARNING, "Cannot (re)configure database navigation tree. No cassandra client found.");
			}
		} else {
			log.log(Level.WARNING, "Cannot (re)configure database navigation tree. UserSession is empty.");
		}
	}

	public List<NavigationNode> getNavigationRoots() {
		return navigationRoots;
	}

	public UserSession getSession() {
		return session;
	}

	public void setSession(UserSession session) {
		this.session = session;
	}
	
}
